package com.zlict.admin.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.zlict.common.utils.DateUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.zlict.admin.mapper.CostTypeTreeMapper;
import com.zlict.admin.domain.CostTypeTree;
import com.zlict.admin.service.ICostTypeTreeService;

/**
 * 费用类型树形Service业务层处理
 * 
 * @author lqh
 * @date 2025-06-21
 */
@Service
@RequiredArgsConstructor
public class CostTypeTreeServiceImpl implements ICostTypeTreeService 
{
    private final CostTypeTreeMapper costTypeTreeMapper;

    /**
     * 查询费用类型树形
     * 
     * @param id 费用类型树形主键
     * @return 费用类型树形
     */
    @Override
    public CostTypeTree selectCostTypeTreeById(String id)
    {
        return costTypeTreeMapper.selectCostTypeTreeById(id);
    }

    /**
     * 查询费用类型树形列表
     * 
     * @param costTypeTree 费用类型树形
     * @return 费用类型树形
     */
    @Override
    public List<CostTypeTree> selectCostTypeTreeList(CostTypeTree costTypeTree)
    {
        return costTypeTreeMapper.selectCostTypeTreeList(costTypeTree);
    }

    /**
     * 新增费用类型树形
     * 
     * @param costTypeTree 费用类型树形
     * @return 结果
     */
    @Override
    public int insertCostTypeTree(CostTypeTree costTypeTree)
    {
        costTypeTree.setCreateTime(DateUtils.getNowDate());
        return costTypeTreeMapper.insertCostTypeTree(costTypeTree);
    }

    /**
     * 修改费用类型树形
     * 
     * @param costTypeTree 费用类型树形
     * @return 结果
     */
    @Override
    public int updateCostTypeTree(CostTypeTree costTypeTree)
    {
        costTypeTree.setUpdateTime(DateUtils.getNowDate());
        return costTypeTreeMapper.updateCostTypeTree(costTypeTree);
    }

    /**
     * 批量删除费用类型树形
     * 
     * @param ids 需要删除的费用类型树形主键
     * @return 结果
     */
    @Override
    public int deleteCostTypeTreeByIds(Long[] ids)
    {
        return costTypeTreeMapper.batchUpdate(ids);
    }


    /**
     * 查询所有树形结构
     * @return
     */
    @Override
    public List<CostTypeTree> selectAllCostTypeTree() {
        String ROOT_NODE_ID = "0"; // 定义根节点ID常量
        try {
            List<CostTypeTree> allNodes = costTypeTreeMapper.selectCostTypeTreeList(null);
            Map<String, CostTypeTree> nodeMap = allNodes.stream()
                    .collect(Collectors.toMap(CostTypeTree::getId, e -> e)); // ID 映射到节点
            List<CostTypeTree> rootNodes = new ArrayList<>();

            for (CostTypeTree node : allNodes) {
                if (Objects.equals(node.getParentId(), ROOT_NODE_ID)) { // 避免空指针异常
                    rootNodes.add(node);
                } else {
                    CostTypeTree parent = nodeMap.get(node.getParentId());
                    if (parent != null) {
                        if (parent.getChildren() == null) {
                            parent.setChildren(new ArrayList<>()); // 初始化子节点列表
                        }
                        parent.getChildren().add(node); // 给父节点添加子节点
                    }
                }
            }

            // 递归设置每个节点的 level 并对子节点进行排序
            for (CostTypeTree rootNode : rootNodes) {
                setLevelRecursively(rootNode, 1); // 根节点的 level 为 1
            }

            // rootNodes 即为树形结构的根节点列表
            return rootNodes;
        } catch (Exception e) {
            throw new RuntimeException("Failed to build the tree structure", e); // 抛出运行时异常
        }
    }

    /**
     * 递归设置树节点的 level 并对子节点进行排序
     * @param node 当前节点
     * @param level 当前层级
     */
    private void setLevelRecursively(CostTypeTree node, int level) {
        node.setLevel(String.valueOf(level)); // 设置当前节点的 level

        // 对子节点进行排序
        if (node.getChildren() != null && !node.getChildren().isEmpty()) {
            // 按 orderSort 升序排序
            node.setChildren(node.getChildren().stream()
                    .sorted(Comparator.comparingInt(e -> Integer.parseInt(e.getOrderSort())))
                    .collect(Collectors.toList()));

            // 递归处理每个子节点
            for (CostTypeTree child : node.getChildren()) {
                setLevelRecursively(child, level + 1); // 递归设置子节点的 level
            }
        }
    }



}
